#include "Controller.h"
#include "MeadeLX200.h"
#include "NexStar.h"
#include "Telescope.h"

Telescope * telescope_new(Controller *controller) {
	Telescope *t = (Telescope *) malloc(sizeof(Telescope));
	t->controller = controller;
	return t;
}

void telescope_start(Telescope *telescope) {
	telescope->sdd = open(telescope->path, O_RDWR | O_NDELAY);
	if(telescope->sdd == ERROR)
		Throw 0;
	tcflush(telescope->sdd, TCIOFLUSH);
	fcntl(telescope->sdd, F_SETFL, fcntl(telescope->sdd, F_GETFL, 0) & ~O_NDELAY);
	switch(telescope->protocol) {
		case MEADE_LX200:
			meade_lx200_start(telescope);
			break;
		case NEXSTAR:
			nexstar_start(telescope);
			break;
		default:
			Throw 0;
			break;
	}
}

void telescope_stop(Telescope *telescope) {
	close(telescope->sdd);
}

void telescope_execute_command(Telescope *telescope, Client *client, uint8_t command, char *params, char *callback) {
	switch(telescope->protocol) {
		case MEADE_LX200:
			meade_lx200_execute_command(telescope, client, command, params, callback);		
		case NEXSTAR:
			nexstar_execute_command(telescope, client, command, params, callback);
			break;
		default:
			Throw 500;
			break;
	}
}

void telescope_read_data(Telescope *telescope, void *data) {
	pthread_mutex_lock(&mutex);
	int rt = read(telescope->sdd, data, 4096);
	pthread_mutex_unlock(&mutex);
	if(rt == ERROR)
		Throw 500;
}


void telescope_write_data(Telescope *telescope, void *data) {
	pthread_mutex_lock(&mutex);
	int rt = write(telescope->sdd & 0xff, data, sizeof(data) + 1);
	pthread_mutex_unlock(&mutex);
	if(rt == ERROR)
		Throw 500;
	wait(3500);
}

void wait(int ms) {
	struct timeval t;
	t.tv_sec = 0;
	t.tv_usec = 1*ms;
	select(0, 0, 0, 0, &t);

}
